<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\Message as MessageModel;

/**
 * 留言管理
 * @package app\admin\controller
 */
class Message extends AdminBase
{
    private $model=null;
    public function _initialize()
    {
        if (is_null($this->model)) {
            $this->model = new MessageModel;
        }
    }
    # 留言列表
    public function index()
    {
        $message=$this->model->getAllData();
        $this->assign('data', $message);
        return $this->fetch();
    }
    # 查看、审核
    public function check()
    {
        if (request()->isGet()) {
            $id=input('get.id');
            if (!$result=$this->model->getDataByWhere(['id'=>$id], '', '', true)) {
                return json(['errno'=>1,'msg'=>'未找到相关数据']);
            }
            $origin=$result->getData();
            if (2===$origin['status']) {
                $status=$this->model->editStatus($id, 0);
            }
            return json(['errno'=>0,'msg'=>'','data'=>$result]);
        } elseif (request()->isPost()) {
            $data=input('post.');
            if (!is_array($data['id'])) {
                if (!$this->model->editStatus(intval($data['id']))) {
                    return json(['errno'=>1,'msg'=>'留言审核时发生错误']);
                }
                return json(['errno'=>0,'msg'=>'留言审核成功']);
            }
            $fail=0;
            foreach ($data['id'] as $value) {
                if (!$this->model->editStatus(intval($value))) {
                    $fail++;
                }
            }
            if (0===$fail) {
                return json(['errno'=>0,'msg'=>'留言审核成功']);
            }
            return json(['errno'=>1,'msg'=>'留言审核时发生错误']);
        }
    }
    # 删除
    public function del()
    {
        if (!request()->isAjax()) {
            $this->resirect('admin/index/home');
        }
        $data=input('post.');
        if (!$result=$this->model->delData($data['id'])) {
            return json(['errno'=>1,'msg'=>'删除留言时发生错误']);
        }
        return json(['errno'=>0,'msg'=>'删除留言成功']);
    }
    # 回复
    public function reply()
    {
        if (!request()->isAjax()) {
            $this->resirect('admin/index/home');
        }
        $data=input('post.');
        $reply['reply']=$data['reply'];
        $reply['reply_time']=request()->time();
        if (!$this->model->editData(['id'=>$data['id']], $reply)) {
            return json(['errno'=>1,'msg'=>'回复留言时发生错误']);
        }
        return json(['errno'=>0,'msg'=>'回复留言成功']);
    }
}
